<?php

function reequipment_userapi_groupdowntime($args)
{
    extract($args);

    // Optional arguments
    if (!isset($startnum)) {$startnum = 1;}
    if (!isset($numitems)) {$numitems = -1;}

    $dbconn =& xarDBGetConn();
    $xartable =& xarDBGetTables();
    $table = $xartable['remaintenance'];

    $query = "SELECT company_id,
    				 MIN(downtime) as min,
    				 MAX(downtime) as max,
    				 AVG(downtime) as avg,
    				 SUM(downtime) as sum,
    				 COUNT(maintenance_id) as count_maintenance_actions"
    		. " FROM $table";     		

    $where = array();
    $bind = array();
    
    if (!empty($company_id)) {
        $where[] = 'company_id = ?';
        $bind[] = (int)$company_id;
    }
    
    if (!empty($where)) {
        $query .= ' WHERE ' . implode(' AND ', $where);
    }

    $result =& $dbconn->SelectLimit($query, $numitems, $startnum-1, $bind);
    if (!$result) return;

    $tags = array();
    for (; !$result->EOF; $result->MoveNext()) {
        list($company_id, $min, $max, $avg, $sum, $count_maintenance_actions) = $result->fields;

        $tags[] = array(
        		'company_id'							=> $company_id,
        		'min'										=> round($min, 2),
                'max' 									=> round($max, 2),
                'avg'										=> round($avg, 2),
                'sum'										=> round($sum, 2),
                'count_maintenance_actions'	=> $count_maintenance_actions
        );
    }

    $result->Close();
    return $tags;
}
?>